// 配置参数
const totalPages = 10; // 最大加载页数
let currentPage = 1; // 当前页码
const dataContainer = document.getElementById('data-container'); // 数据展示容器
const loadingElement = document.getElementById('loading'); // 加载提示元素

// 加载数据的函数
async function loadData(page) {
    loadingElement.style.display = 'block'; // 显示加载提示
    try {
        const response = await fetch(`/matchs?page=${page}`);
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        const data = await response.json();
        displayData(data);
    } catch (error) {
        console.error('Fetch error:', error);
        alert('加载数据时出错，请重试。');
    } finally {
        loadingElement.style.display = 'none'; // 隐藏加载提示
    }
}

// 展示数据的函数
function displayData(data) {
    data.forEach(item => {
        console.log(item);
        const div = document.createElement('div');
        time = timestampToLocalTime(item.start_time)
        //div.textContent = item; // 假设数据有content字段
        rf='';
       if (item.performance === null || item.performance === undefined || item.performance === '') {
            rf = '';
        } else if (item.performance.charAt(0) === 'W') {
            rf = '√';
        } else if (item.performance.charAt(0) === 'P') {
            rf = 'PUSH';
        } else {
            rf = 'x';
        }


        div.innerHTML = `<div class="match-item"><div class="match-info"><h2>${item.league}</h2><p>${item.home} - ${item.away}</p ><div class="recommendation"><p>Prediction：${item.prediction}<span class="correct">${rf} ${item.score}</span></p ></div></div><div class="match-time">Match Time：${time}</div><div class="match-result"></div></div>`

        dataContainer.appendChild(div);
    });
}

// 滚动事件处理函数
function handleScroll() {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 50) {
        // 滚动到底部，加载下一页
        if (currentPage < totalPages) {
            currentPage++;
            loadData(currentPage);
        } else {
            console.log('已加载所有数据');
        }
    }
}

// 节流函数，防止频繁触发
function throttle(func, wait) {
    let timeout = null;
    return function() {
        if (!timeout) {
            timeout = setTimeout(() => {
                func.apply(this, arguments);
                timeout = null;
            }, wait);
        }
    };
}
function timestampToLocalTime(timestamp) {
    if (typeof timestamp !== 'number' || isNaN(timestamp)) {
        throw new Error('Invalid timestamp');
    }
    let date = new Date(timestamp);
    if (isNaN(date.getTime())) {
        throw new Error('Invalid date');
    }
    let year = date.getFullYear();
    let month = pad(date.getMonth() + 1);
    let day = pad(date.getDate());
    let hours = pad(date.getHours());
    let minutes = pad(date.getMinutes());

    return `${year}-${month}-${day} ${hours}:${minutes}`;
}

function pad(num) {
    return num.toString().padStart(2, '0');
}

// Example usage:
let timestamp = 1630456800000;
try {
    console.log(timestampToLocalTime(timestamp));  // Output: "2021-09-01 00:00:00"
} catch (error) {
    console.error(error.message);
}

// 初始化加载第一页
loadData(currentPage);

// 添加滚动事件监听器，使用节流优化
window.addEventListener('scroll', throttle(handleScroll, 500));

// 添加登录状态检查函数
function isLoggedIn() {
  return !!localStorage.getItem('authToken'); // 假设使用localStorage存储token
}



// 登录表单处理
document.getElementById('loginForm')?.addEventListener('submit', async (e) => {
  e.preventDefault();

    const formData = new URLSearchParams();
  formData.append('username', e.target[0].value);
  formData.append('password',  e.target[1].value);

  try {
    const response = await fetch('/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: formData
    });

    if (response.ok) {

      const data = await response.json();
      console.log(data);
      localStorage.setItem('authToken', data.token);
      hideLoginModal();
      window.location.href = '/user';
    } else {
      alert('登录失败，请检查用户名密码');
    }
  } catch (error) {
    console.error('登录错误:', error);
    alert('网络错误，请稍后重试');
  }
});
